<template>
  <PageContainer>
    <view class="container">
      <Header title="核验签到" />
      <view class="pa-16">
        <view class="fz-16 default-color mb-12">
          <text>{{ activityTitle }}</text>
        </view>
        <view class="disFlxJS" style="gap: 24rpx">
          <view class="pa-16 stats-view br-8">
            <view class="mb-4 fz-12"><text>成功报名人数</text></view>
            <view>
              <text class="fz-24 fw-7">{{ activityCountInfo?.passedNumByCurrentTenant || 0 }}</text>
              <text class="fz-12">人</text>
            </view>
          </view>
          <view class="pa-16 stats-view br-8">
            <view class="mb-4 fz-12"><text>签到人数</text></view>
            <view>
              <text class="fz-24 fw-7">
                {{ activityCountInfo?.registerSignNumByCurrentTenant || 0 }}
              </text>
              <text class="fz-12">人</text>
            </view>
          </view>
        </view>
      </view>
      <view class="pa-16 disFlxCC">
        <view class="fz-12 default-color mb-16">
          <text>请将需要核验的凭证二维码对齐至下方窗口扫描</text>
        </view>
        <view style="width: 600rpx; height: 600rpx">
          <camera
            v-if="showCamera"
            mode="scanCode"
            resolution="high"
            device-position="back"
            flash="auto"
            frame-size="small"
            @scancode="handleScancode"
            @error="handleError"
            style="width: 100%; height: 100%"
          />
          <view
            v-else
            class="disFlxCC"
            style="width: 100%; height: 100%; background-color: #f2f3f5"
          >
            <text class="fz-16 default-color">{{ errMsg }}</text>
          </view>
        </view>
      </view>

      <TButtonGroup
        :styles="{
          backgroundColor: '#fff',
          boxShadow: '0px -4rpx 24rpx 0px rgba(150, 151, 153, 0.16)',
        }"
      >
        <TButton
          class="gutter-btn"
          text="手动输码签到"
          type="none"
          custom-class="br-24"
          :custom-style="{
            color: '#2878FF',
            border: '1px solid #2878FF',
            boxSizing: 'content-box',
          }"
          @click="inputCodeCheckVisible = true"
        />
      </TButtonGroup>
    </view>

    <SelectPrinter
      v-if="activityId"
      ref="selectPrinterRef"
      v-model:is-empty="printerIsEmpty"
      :activity-id="activityId"
    />
    <ShowModal
      v-model="modalVisible"
      title="核验并签到成功！"
      cancel-text="不打印"
      cancel-color="#969799"
      :confirm-text="printerIsEmpty || !registerId ? '确定' : '打印胸卡'"
      :confirm-color="printerIsEmpty || !registerId ? '#E44435' : '#2878FF'"
      :show-cancel="!printerIsEmpty || !registerId"
      @confirm="handleShowPrinterPopup"
    >
      <template #content>
        <view class="disFlxCC pb-24" style="color: #2878ff">
          <text v-if="ticketName" class="fz-24 my-8">{{ ticketName }}</text>
          <text class="fz-18">凭证码：{{ consumeNoRef }}</text>
        </view>
      </template>
    </ShowModal>
    <ShowModal
      v-model="inputCodeCheckVisible"
      title="输入凭证数字码"
      cancel-text="取消"
      cancel-color="#969799"
      confirm-text="马上核验"
      confirm-color="#E44435"
      :is-mask-click="false"
      :confirm-auto-close="false"
      @confirm="handleInputCodeCheck"
    >
      <template #content>
        <UniEasyinput v-model="verificationCode" placeholder="输入数字码" />
      </template>
    </ShowModal>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* adminSignedIt 扫码核票(管理员代签到) */
  import { activityManagerScanVerification, getActivityCountInfo } from '@/api/activity';
  import type { IActivityCountInfo } from '@/api/activity/types';
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import SelectPrinter from '../../components/SelectPrinter.vue';
  import ShowModal from '@/components/ShowModal/index.vue';
  import { SignTypeEnum } from '@/enums/activityStatusEnum';
  import { useAuthSetting } from '@/hooks/core/useAuthSetting';
  import { onLoad } from '@/router';
  import { Toast } from '@/utils';
  import { onShow } from '@dcloudio/uni-app';
  import { ref } from 'vue';
  import { useDebounceFn } from '@/hooks/core/useDebounceFn';

  const { authErrorCallbak } = useAuthSetting();

  const printerIsEmpty = ref(false);

  const showCamera = ref(true);
  const activityCountInfo = ref<IActivityCountInfo>();
  const activityId = ref<number>();
  const activityTitle = ref<string>('');
  onLoad<'adminSignedIt'>(async (op) => {
    activityTitle.value = op.activityTitle;
    activityId.value = op.activityId;
    getCountInfo();
  });

  async function getCountInfo() {
    const res = await getActivityCountInfo(activityId.value as number);
    activityCountInfo.value = res;
  }

  onShow(() => (showCamera.value = true));

  const isRunning = ref(false);
  const lastCode = ref<string>()
  const handleScancode = useDebounceFn((e: any) => {
    const code = e.detail.result;
    if (code === lastCode.value || isRunning.value || modalVisible.value || inputCodeCheckVisible.value) {
      return;
    }
    isRunning.value = true;
    lastCode.value = code
    handleVerification(code, SignTypeEnum.ADMIN_SCAN_SIGN_IN).finally(
      () => (isRunning.value = false),
    );
  }, 500);

  const errMsg = ref<string>();
  async function handleError(e: any) {
    console.log('handleError', e);
    showCamera.value = false;
    const isAuth = await authErrorCallbak('camera', { errno: 0, errMsg: e.detail.errMsg });
    if (isAuth) {
      errMsg.value = '相机调用失败';
    }
  }

  const inputCodeCheckVisible = ref(false);
  const verificationCode = ref<string>('');
  function handleInputCodeCheck() {
    if (!verificationCode.value) {
      Toast('请输入数字码');
      return;
    }
    handleVerification(verificationCode.value, SignTypeEnum.ADMIN_INPUT_SIGN_IN).then(() => {
      inputCodeCheckVisible.value = false;
      verificationCode.value = '';
    });
  }

  const modalVisible = ref(false);
  const registerId = ref<number>();
  const ticketName = ref<string>()
  const consumeNoRef = ref<string>()
  async function handleVerification(consumeNo: string, signType: SignTypeEnum) {
    if (!activityId.value) return;
    ticketName.value = ''
    consumeNoRef.value = ''
    const res = await activityManagerScanVerification({
      activityId: activityId.value,
      consumeNo,
      signType,
    });
    getCountInfo();
    consumeNoRef.value = consumeNo
    ticketName.value = res.ticketName
    registerId.value = res.id;
    modalVisible.value = true;
  }

  const selectPrinterRef = ref<{ show: (registerId: number) => void }>();
  function handleShowPrinterPopup() {
    if (printerIsEmpty.value || !registerId.value) {
      modalVisible.value = false;
      return;
    }
    selectPrinterRef.value?.show(registerId.value);
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background-color: #fff;
  }
  .stats-view {
    flex: 1;
    color: #2878ff;
    background-color: #f2f3f5;
  }
</style>
